using System.Text.Json;
using HKH.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SyncService.Results;

namespace SyncService.WebHost.Filters
{
    public class ExceptionFilter : IExceptionFilter
    {
        private readonly ILogger _logger;

        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            _logger = logger;
        }
        void IExceptionFilter.OnException(ExceptionContext context)
        {
            _logger.LogError(context.Exception, context.Exception.Message);
            var result = new ContentResult()
            {
                ContentType = "application/json",
            };

            if (context.Exception is UnLogException)
            {
                result.StatusCode = 200;
                result.Content = JsonSerializer.Serialize(new ApiResult(-1, context.Exception.Message));
            }
            else
            {
                _logger.LogError(context.Exception, "fail");
                result.StatusCode = 500;
                result.Content = JsonSerializer.Serialize(new ApiResult(-1, context.Exception.Message));
            }
            context.Result = result;
        }
    }
}